package contents;

import contents.entities.Absence;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.SQLException;

import contents.entities.Class;
import contents.entities.DateSubstitutions;
import contents.entities.NoticeboardNotice;
import contents.entities.Subject;
import contents.entities.SubjectGrades;
import contents.entities.SubstitutionItem;
import contents.entities.Teacher;
import database.Database;
import database.DatabaseEntities;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

public class TeacherContent {

    public static HttpServletRequest setContent(HttpServletRequest request) throws SQLException, ParseException {
        String contentRequest = (String) request.getParameter("content");
        
        if (contentRequest == null) {
            // do nothing
        } else if (contentRequest.equals("noticeboards")) {
            request = setNoticeboardsContent(request);
        } else if (contentRequest.equals("deleteNotice")) {
            deleteNotice(request);
        } else if (contentRequest.equals("addNotice")) {
            addNotice(request);
        } else if (contentRequest.equals("grades")) {
            request = setGradesContent(request);
        } else if (contentRequest.equals("saveGrades")) {
            saveGrades(request);
        } else if (contentRequest.equals("showTimetable")) {
            request = TimetablesContent.setContent(request);
        } else if (contentRequest.equals("substitutions")) {
            request = setSubstitutionsContent(request);
        } else if (contentRequest.equals("reportAbsence")) {
            request = setReportAbsenceContent(request);
        } else if (contentRequest.equals("deleteAbsence")) {
            deleteAbsence(request);
        } else if (contentRequest.equals("addAbsence")) {
            request = addAbsence(request);
        }
        
        return request;
    }
    
    private static HttpServletRequest setNoticeboardsContent(HttpServletRequest request) throws SQLException {
        String classIdString = request.getParameter("classId");
        
        if (classIdString == null) {
            Map<Integer, Class> classes = Database.selectClasses();
            request.setAttribute("classes", classes.values());
            
        } else {
            int classId = Integer.valueOf(classIdString);
            
            String className = Database.selectClassName(classId);
            request.setAttribute("className", className);
            
            Map<Integer, NoticeboardNotice> notices = Database.selectNoticesForTeacher(classId);
            request.setAttribute("notices", notices.values());
        }
        
        return request;
    }
    
    private static void deleteNotice(HttpServletRequest request) throws SQLException {
        int noticeId = Integer.valueOf(request.getParameter("noticeId")).intValue();
        
        HttpSession session = request.getSession();
        int teacherId = ((Integer) session.getAttribute("userId")).intValue();
        
        Database.deleteNotice(noticeId, teacherId);
    }
    
    private static void addNotice(HttpServletRequest request) throws SQLException {
        HttpSession session = request.getSession();
        int teacherId = ((Integer) session.getAttribute("userId")).intValue();
        
        int classId = Integer.valueOf(request.getParameter("classId"));
        String text = request.getParameter("text");
        String type = request.getParameter("type");
        
        Database.addNotice(teacherId, classId, text, type);
    }
    
    private static HttpServletRequest setGradesContent(HttpServletRequest request) throws SQLException {      
        HttpSession session = request.getSession();
        int teacherId = ((Integer) session.getAttribute("userId")).intValue();

        String classIdString = request.getParameter("classId");
        
        if (classIdString == null) {
            List<contents.entities.ClassesSubjectsOfTeacher> classesSubjects = Database.selectClassesSubjectsOfTeacher(teacherId);
            Map<Integer, contents.entities.ClassesSubjectsOfTeacher> classesSubjectsMap = new HashMap<Integer, contents.entities.ClassesSubjectsOfTeacher>();
            for (int i = 0; i < classesSubjects.size(); i++) {
                classesSubjectsMap.put(i+1, classesSubjects.get(i));
            }
            
            request.setAttribute("classesSubjects", classesSubjectsMap.values());
        } else {
            int classId = Integer.valueOf(classIdString).intValue();
            int subjectId = Integer.valueOf(request.getParameter("subjectId")).intValue();
            
            if (Database.teacherTeachesClassSubject(teacherId, classId, subjectId)) {
                Subject subject = Database.getSubject(subjectId);
                request.setAttribute("subject", subject);
                String className = Database.selectClassName(classId);
                request.setAttribute("className", className);
                
                Map<Integer, SubjectGrades> subjectGrades = Database.selectGradesOfClassAndSubject(classId, subjectId);
                request.setAttribute("gradebooks", subjectGrades.values());
            } else {
                throw new SQLException("setGradesContent: You do not teach subject in the class, you can not write grades there.");
            }
        }
        
        return request;
    }
    
    private static void saveGrades(HttpServletRequest request) throws SQLException {
        HttpSession session = request.getSession();
        int teacherId = ((Integer) session.getAttribute("userId")).intValue();
        
        int classId = Integer.valueOf(request.getParameter("classId")).intValue();
        int subjectId = Integer.valueOf(request.getParameter("subjectId")).intValue();
        
        if (Database.teacherTeachesClassSubject(teacherId, classId, subjectId)) {
            String suffix = request.getParameter("suffix");
            if (suffix.equals("x") ||
                    !(suffix.equals("p") || suffix.equals("o") || suffix.equals("d") || suffix.equals("s") || suffix.equals("i"))) {
                suffix = "";
            }
            
            List<SubjectGrades> subjectGrades = new ArrayList<SubjectGrades>();
            
            String gradesURL = request.getParameter("grades");
            while (!gradesURL.equals("")) {
                int GPosition = gradesURL.indexOf('G');
                int gradebookId = Integer.valueOf(gradesURL.substring(0, GPosition)).intValue();
                gradesURL = gradesURL.substring(GPosition+1);
                
                int XPosition = gradesURL.indexOf('X');
                String grades = gradesURL.substring(0, XPosition) + suffix;
                gradesURL = gradesURL.substring(XPosition+1);
                
                subjectGrades.add(new SubjectGrades(gradebookId, null, null, grades));
            }
            
            Database.setGrades(classId, subjectId, subjectGrades);
            
        } else {
            throw new SQLException("saveGrades: You do not teach subject in the class, you can not save grades there.");
        }
    }
        
    private static HttpServletRequest setSubstitutionsContent(HttpServletRequest request) throws SQLException {
        Map<Integer, DateSubstitutions> dateSubstitutions = new HashMap<Integer, DateSubstitutions>();
        
        HttpSession session = request.getSession();
        int teacherId = ((Integer) session.getAttribute("userId"));
        
        // get next monday date
        Date mondayDate = common.CommonMethods.getMondayDate();

        Date currentDate;
        for (int i = 0; i < 5; i++) {
            currentDate = new Date(mondayDate.getTime());
            currentDate.setDate(currentDate.getDate() + i);

            // get substitutions of the day and of student's class
            List<DatabaseEntities.Substitution> substitutions = Database.selectSubstitutionsOfDateAndTeacher(currentDate, teacherId);
            
            List<SubstitutionItem> substitutionItems = new ArrayList<SubstitutionItem>();
            
            for (int j = 0; j < substitutions.size(); j++) {
                DatabaseEntities.Substitution substitution = substitutions.get(j);
                
                String className = Database.selectClassName(substitution.classId);
                Integer lesson = Integer.valueOf(substitution.unit);
                Subject subject = Database.getSubject(substitution.subjectId);
                Teacher missingTeacher = Database.getTeacher(substitution.missingTeacherId);
                
                Teacher substitutingTeacher;
                if (substitution.substitutingTeacherId == null) {
                    substitutingTeacher = null;
                } else {
                    substitutingTeacher = Database.getTeacher(substitution.substitutingTeacherId.intValue());
                }
            
                substitutionItems.add(new SubstitutionItem(className, lesson, subject, missingTeacher, substitutingTeacher));
            }
            Collections.sort(substitutionItems, new SubstitutionItem.ByClassNameAndTimeComparator());
            
            dateSubstitutions.put(i, new DateSubstitutions(currentDate, substitutionItems));
        }
        
        request.setAttribute("substitutionsList", dateSubstitutions.values());
        return request;
    }
        
    private static HttpServletRequest setReportAbsenceContent(HttpServletRequest request) throws SQLException {
        HttpSession session = request.getSession();
        int teacherId = ((Integer) session.getAttribute("userId")).intValue();
        
        java.util.Date tomorrowDate = new java.util.Date();
        tomorrowDate.setDate(tomorrowDate.getDate() + 1);
        Map<Integer, Absence> absences = Database.selectAbsencesOfTeacherSinceDate(teacherId, tomorrowDate);
        
        request.setAttribute("absences", absences.values());
        return request;
    }
    
    private static void deleteAbsence(HttpServletRequest request) throws SQLException {
        int absenceId = Integer.valueOf(request.getParameter("absenceId")).intValue();
        
        HttpSession session = request.getSession();
        int teacherId = ((Integer) session.getAttribute("userId")).intValue();
        
        Database.deleteAbsence(absenceId, teacherId);
    }
    
    private static HttpServletRequest addAbsence(HttpServletRequest request) throws SQLException, ParseException {
        HttpSession session = request.getSession();
        int teacherId = ((Integer) session.getAttribute("userId")).intValue();
        
        String dateString = request.getParameter("date");
        java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("dd.MM.yyyy");
        java.util.Date date = dateFormat.parse(dateString);
        java.util.Date currentDate = new java.util.Date();
        if (currentDate.compareTo(date) >= 0) {
            request.setAttribute("result", "failed");
            return request;
        }
        
        int fromUnit = Integer.valueOf(request.getParameter("fromUnit"));
        int toUnit = Integer.valueOf(request.getParameter("toUnit"));
        
        Database.addAbsence(teacherId, date, fromUnit, toUnit);
        return request;
    }
    
    private TeacherContent() {
    }
}
